package com.terrace.core.mybatis.plugin.pagination.sqlsource;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;

import com.terrace.core.mybatis.plugin.pagination.PaginationHandler;
import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.mybatis.plugin.pagination.parser.OrderByParser;

/**
 * 支持orderby和分页
 *
 * @author liuzh
 * @since 2015-06-27
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class CustomStaticSqlSource extends PaginationSqlSource {
	
    private String sql;
    
    private List<ParameterMapping> parameterMappings;
    
    private Configuration configuration;
    
    private SqlSource original;

    public CustomStaticSqlSource(StaticSqlSource sqlSource) {
        MetaObject metaObject = SystemMetaObject.forObject(sqlSource);
        this.sql = (String) metaObject.getValue("sql");
        this.parameterMappings = (List<ParameterMapping>) metaObject.getValue("parameterMappings");
        this.configuration = (Configuration) metaObject.getValue("configuration");
        this.original = sqlSource;
    }
    
    @Override
    protected BoundSql getDefaultBoundSql(Object parameterObject) {
    	return new BoundSql(configuration, sql, parameterMappings, parameterObject);
    }

    @Override
    protected BoundSql getCountBoundSql(Object parameterObject) {
        return new BoundSql(configuration, THREAD_LOCAL_PARSER.get().getCountSQL(sql), parameterMappings, parameterObject);
    }

	@Override
	protected BoundSql getPaginationBoundSql(Object parameterObject) {
        String tempSql = sql;
        Pagination pagination = PaginationHandler.getLocalPagination();
        if (StringUtils.isNotBlank(pagination.getSort())) {
            tempSql = OrderByParser.converToOrderBySql(sql, pagination.getSort(), pagination.getOrder());
        }
        tempSql = THREAD_LOCAL_PARSER.get().getPaginationSQL(tempSql);
        return new BoundSql(configuration, tempSql, THREAD_LOCAL_PARSER.get().getPageParameterMapping(configuration, original.getBoundSql(parameterObject)), parameterObject);
	}

}
